package services

import (
	"errors"
	"shop/database"
	"shop/model"
	"shop/pkg/constant"
	e "shop/pkg/err"
	"shop/pkg/utils"
)

var db = database.GetDB()

func Login(name, password string) (token string, e error) {
	token = ""
	u := model.User{}
	db.Where("username = ? and password = ?", name, password).First(&u).Debug()
	if u == (model.User{}) {
		e = errors.New("userName or passWord error")
		return
	}
	token = utils.CreateToken(u)
	utils.ParseToken(token)
	return
}

func GetById(id int64) model.User {
	u := model.User{}
	if err := db.Where("id = ?", id).First(&u).Error; err != nil {
		panic(e.ApiError{ErrorCode: constant.ErrUserNot})
	}
	return u
}

func DeleteById(id int64) {
	u := model.User{}
	db.Where("id = ?", id).Delete(&u)
}

func Add(user model.User) {
	if err := db.Create(&user).Error; err != nil {
		panic(e.ApiError{ErrorCode: constant.ErrUserNameExits})
	}
}
